#include "key_event.hpp"
#include "stdio.h"
#include "system.h"


/*!
* @brief    按键检测事件 可检测长按和连按
* @return   返回当前的按键类型
*/
int KEYEvent::keyEvent(unsigned int ms_count){
    static unsigned int press_time = 0;     //当前按下的时间
    static unsigned int last_press_time = 0;    //记录上一次按下的时间
    static unsigned int last_release_time = 0;  //记录上一次松开的时间
    static unsigned int elapsed_time = 0;   //按键持续时间
    static unsigned int press_count = 0;    //记录按下的次数
    static unsigned int press_type = 0;     //按键类型

    if( this->get() == true){
        /* 首次按下 */
        if( this->is_pressed != true){
            press_time = ms_count;
            System_delayMs(20);
            if(this->get() == true){
                is_pressed = true;
                if( press_count == 0) press_count ++;
                if( press_count > 0){
                    if( ms_count - last_press_time < 500){
                        press_count++;
                    }
                }  
                last_press_time = ms_count;    
            }
        }
        /* 长按 */
        else{
            if( press_count != 0){
                elapsed_time = ms_count - press_time;
                if( elapsed_time > 3000){  // 长按超过 3 秒
                    press_count = 0;
                    press_time = 0;
                    press_type = long_pressed_3s;
                    elapsed_time = 0;  // 清零 elapsed_time，防止误判
                }
                return press_type;
            }else press_type = none_clicked;
        }
    }
    /* 按键松开 或者 无按键*/
    else{
        if( is_pressed == true){
            last_release_time = ms_count;
            is_pressed = false;

            // 如果在松开时已经触发了长按，则直接清除
            if (press_type == long_pressed_3s) {
                press_count = 0;
                press_time = 0;
                press_type = none_clicked;
            }
        }
        /* 无按键 或者 最后一次按键结束后*/
        else{
            if(press_count > 0){
                if( ms_count - last_release_time > 500){
                    if ( press_count == one_clicked) press_type = one_clicked;
                    else if( press_count == double_clicked) press_type = double_clicked;
                    else if( press_count == triple_clicked) press_type = triple_clicked;
                    else press_type = none_clicked;
                    press_count = 0; // 重置按下次数
                }
            }else press_type = none_clicked;
        }

    }
    return press_type;
}



